#!/usr/bin/perl -w

#use strict;

#$in1 = "111.txt";
$in1 = "Gm12878CtcfV2.example_MACS_wiggle/treat/Gm12878CtcfV2_all.wig";
$in2 = "Gm12878CtcfV2.example_peaks.bed";
$out = "wig-peak-2k.wig";

open(IN1, $in1) or die("can't open $in1");
open(IN2, $in2) or die("can't open $in2");
open(OUT, ">$out") or die("can't open $out");

$peak_range = 2000;

my($peak, $line, $chr, $chr_count);

while(<IN2>)
{
	#chomp; #
	/(.*)\t(\d*)\t(\d*)\t/;
	#print "$1 $2 $3\n"; exit;
	$chr_count->{$1} += 1;
	$peak->{$1}->{$chr_count->{$1} - 1} = "$2\t$3"; # start end, sorted
}

my($cur_peak, $i, $start, $end);
#my $len;
while(<IN1>)
{
	chomp; #
	$line = $_;
	if(/track/)
	{
		# write out first
		print OUT "$line\n"; #

		$line = <IN1>;
		print OUT "$line\n"; #

		#$line =~ /.*=(chr\d*)/; # chrX ?
		$line =~ /.*=(chr[\d\w]*)/; # chrX ?
		$chr = $1;
		#print $chr, "\n"; exit; #
		$line = <IN1>;
		
		$cur_peak = $peak->{$chr}; #
		$i = 0;
	}
	$line =~ /(.*)\t(.*)$/; # may be float ?
	$pos = $1 + 0;
	$rich = $2 + 0;
	#print "$chr $pos $rich\n"; exit; #

LAST1:
	while($i < $chr_count->{$chr})
	{
		#print "i=$i $peak->{$chr}->{$i}\n"; exit; #
		$peak->{$chr}->{$i} =~ /(\d*)\t(\d*)/;
		$start = $1 - $peak_range;
		$end = $2 + $peak_range;
		#print "i=$i start=$start end=$end pos=$pos\n"; #exit; #
		
		# check ...
		if($pos <= $start - 10)
		{
			last LAST1;
		}

		if(($pos > $start - 10) && ($pos < $end)) # BED space = 10
		{
			# write out
			#print "$pos\t$rich\n"; exit; #
			print OUT "$pos\t$rich\n"; #
			last LAST1;
		}
		$i++;
	}
}

